package com.hh.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hh.eduservice.entity.EduSubject;
import com.hh.eduservice.entity.SubjectData;
import com.hh.eduservice.entity.subject.OneSubject;
import com.hh.eduservice.entity.subject.TwoSubject;
import com.hh.eduservice.mapper.EduSubjectMapper;
import com.hh.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.eduservice.utils.EduSubjectListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author huhuan
 * @since 2021-10-12
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
    @Autowired
    private EduSubjectMapper eduSubjectMapper;

    @Override
    public void addSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try {
            InputStream in = file.getInputStream();
            // 读取表格内容，封装为实体类SubjectData，监听器是EduSubjectListener，将EduSubjectService作为参数传递
            EasyExcel.read(in, SubjectData.class, new EduSubjectListener(eduSubjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ArrayList<OneSubject> getTreeList() {
        // 查询所有一级分类
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("parent_id", "0");
        ArrayList<EduSubject> eduSubjectParents = (ArrayList<EduSubject>) eduSubjectMapper.selectList(wrapper);

        // 查询所有二级分类
        QueryWrapper wrapper2 = new QueryWrapper();
        wrapper2.ne("parent_id", "0");
        ArrayList<EduSubject> eduSubjects = (ArrayList<EduSubject>) eduSubjectMapper.selectList(wrapper2);

        // 封装一级分类
        ArrayList<OneSubject> resultList = new ArrayList<>();
        for (EduSubject eduSubjectParent : eduSubjectParents) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubjectParent, oneSubject);

            ArrayList<TwoSubject> twoSubjects = new ArrayList<>();
            for (EduSubject eduSubject : eduSubjects) {
                if (eduSubject.getParentId().equals(eduSubjectParent.getId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(eduSubject, twoSubject);
                    twoSubjects.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjects);
            resultList.add(oneSubject);
        }
        return resultList;
    }
}
